package com.sly.fuxi.kafka.config;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author SLY
 * @date 2025/3/3
 */
@Configuration
public class KafkaProducerConfig {

    @Value("${spring.kafka.bootstrap-servers}")
    private String bootstrapServers;

    @Bean("specificProducerFactory")
    public ProducerFactory<String, String> specificProducerFactory() {
        Map<String, Object> configProps = new HashMap<>(16);
        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        //
        configProps.put(ProducerConfig.LINGER_MS_CONFIG, 100);
        // 为特定主题指定自定义分区器
        configProps.put(ProducerConfig.PARTITIONER_CLASS_CONFIG, KafkaPartitioner.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }

    @Bean("specificKafkaTemplate")
    public KafkaTemplate<String, String> specificKafkaTemplate(ProducerFactory<String, String> specificProducerFactory) {
        return new KafkaTemplate<>(specificProducerFactory);
    }
}
